<template>
  <a-layout style="height: 100%">
    <a-layout-header class="!px-4.5">
      <div class="flex items-center justify-center h-full text-white">
        <div class="text-lg"> 高速公路收费员服务质量管理软件 </div>
        <div class="flex-1 pl-3">
          <a-button v-show="hideMenu" type="text" @click="menuDrawerVisible = !menuDrawerVisible">
            <template #icon>
              <VerticalRightOutlined v-if="menuDrawerVisible" class="!text-white" />
              <VerticalLeftOutlined v-else class="!text-white" />
            </template>
          </a-button>
        </div>
        <a-dropdown>
          <div class="flex flex-row items-center">
            <!-- <img :src="DEFAULT_IMG_BASE64_STR" class="w-9 h-9 rounded-full mr-2 hidden xxs:inline-block" /> -->
            <UserOutlined class="!text-white text-2xl" />
            <span class="font-medium mx-2">{{ userInfo.userName }}</span>
            <DownOutlined class="!text-white" />
          </div>
          <template #overlay>
            <a-menu class="sl-dropdown-menu">
              <a-menu-item key="1">
                <template #icon>
                  <LockOutlined />
                </template>
                修改密码
              </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="2">
                <template #icon>
                  <LogoutOutlined />
                </template>
                <a @click="doLogout">{{ t("aiot.home.logout") }}</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-layout-header>
    <a-layout>
      <component
        :is="hideMenu ? Drawer : LayoutSider"
        v-model:collapsed="collapsed"
        v-model:visible="menuDrawerVisible"
        :width="200"
        breakpoint="xl"
        collapsed-width="40"
        theme="dark"
        placement="left"
        :closable="false"
        :body-style="hideMenu ? { padding: 0 } : ''"
      >
        <div class="h-full flex flex-col overflow-hidden">
          <div class="flex-1 overflow-auto">
            <a-menu
              v-model:selectedKeys="menuSelKeys"
              v-model:openKeys="subMenuSelKeys"
              mode="inline"
              theme="dark"
              class="sl-menu"
              @open-change="onSubMenuOpenChange"
            >
              <component :is="el.children ? SubMenu : MenuItem" v-for="el in menuStore.menuData" :key="el.path">
                <template v-if="el.children" #title>
                  <span>{{ el.menuName }}</span>
                </template>
                <a v-if="!el.children" href="javascript:void(0)" @click="pushRoute(el.path)">
                  {{ el.menuName }}
                </a>
                <!-- <router-link v-if="!el.children" :to="el.action"> {{ el.name }} </router-link> -->
                <template #icon>
                  <Icon v-if="el.icon" :type="el.icon" />
                </template>
                <template v-if="el.children">
                  <a-menu-item v-for="subEl in el.children" :key="subEl.path">
                    <a href="javascript:void(0)" @click="pushRoute(subEl.path)">{{ subEl.menuName }}</a>
                    <!-- <router-link :to="subEl.action">
                    {{ subEl.name }}
                  </router-link> -->
                    <template #icon>
                      <Icon v-if="subEl.icon" :type="subEl.icon" />
                    </template>
                  </a-menu-item>
                </template>
              </component>
            </a-menu>
          </div>
          <div v-show="!hideMenu" :class="[collapsed ? '' : 'text-right py-1 px-2']">
            <a-button type="text" @click="collapsed = !collapsed">
              <template #icon>
                <VerticalLeftOutlined v-if="collapsed" class="!text-white" />
                <VerticalRightOutlined v-else class="!text-white" />
              </template>
            </a-button>
          </div>
        </div>
      </component>
      <a-layout id="home-content" class="relative overflow-hidden">
        <a-layout-content :class="[homeStore.contentScrollable ? 'overflow-auto' : 'overflow-hidden']">
          <router-view v-show="!homeStore.pageLoading" />
          <div v-show="homeStore.pageLoading" class="text-center pt-5 z-1050">
            <a-spin size="large" :spinning="true"></a-spin>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
    <div
      v-show="homeStore.loading"
      class="absolute inset-0 flex justify-center items-center bg-white bg-opacity-30 z-1050"
    >
      <a-spin :tip="homeStore.loadingText" :spinning="homeStore.loading"></a-spin>
    </div>
    <!-- 解决按需加载问题 -->
    <a-modal :visible="false" />
  </a-layout>
</template>

<script lang="ts" setup>
import {
  VerticalLeftOutlined,
  VerticalRightOutlined,
  UserOutlined,
  DownOutlined,
  LockOutlined,
  LogoutOutlined,
} from "@ant-design/icons-vue";
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { Menu, Drawer, Layout } from "ant-design-vue";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { useHomeStore } from "/@/stores/home";
import { useMenuStore } from "/@/stores/menu";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import Icon from "/@/components/Icon.vue";
import resizer from "/@/utils/resizer";
import router from "/@/router";
import authCache from "/@/utils/cache/authCache";
import type { MenuItem as MenuItemModel } from "/@/api/home/menu/models";
import { UserDetail } from "/@/api/home/user/models";
import env from "/@/base/env";

const SubMenu = Menu.SubMenu;
const MenuItem = Menu.Item;
const LayoutSider = Layout.Sider;

const homeStore = useHomeStore();
const menuStore = useMenuStore();
const { t } = useI18n();
const menuSelKeys = ref<string[]>([]);
const subMenuSelKeys = ref<string[]>([]);
const collapsed = ref(false);
const route = useRoute();
const userInfo = ref<UserDetail>({
  userId: -1,
  userName: "--",
});
//找到菜单的上级菜单 然后展开
function expandRootMenu(path) {
  if (subMenuSelKeys.value.includes(path)) return;
  const data = menuStore.menuData;
  for (let i = 0; i < data.length; i++) {
    const ii = data[i];
    if (ii.path === path) {
      //第一层的不管
      return;
    }
    if (ii.children && ii.children.length > 0) {
      for (let j = 0; j < ii.children.length; j++) {
        const jj = ii.children[j];
        if (jj.path === path) {
          subMenuSelKeys.value = [ii.path, ...subMenuSelKeys.value];
          return;
        }
      }
    }
  }
}
//根菜单图标是否带选中效果
function isRootMenuActive(el: MenuItemModel) {
  if (subMenuSelKeys.value.indexOf(el.path) !== -1 || menuSelKeys.value.indexOf(el.path) !== -1) {
    return true;
  }
  if (el.children) {
    for (let ch of el.children) {
      if (menuSelKeys.value.indexOf(ch.path) !== -1) {
        return true;
      }
    }
  }
  return false;
}
onBeforeRouteUpdate((e) => {
  if (e.path.includes("404") || e.path.includes("401")) return;
  menuSelKeys.value = [e.path];
  expandRootMenu(e.path);
});
const hideMenu = ref(false);
let resizerId;
onMounted(() => {
  menuSelKeys.value = [route.path];
  expandRootMenu(route.path);
  let isFirst = true;
  resizerId = resizer.add(
    () => {
      if (document.body.offsetWidth < 768) {
        if (!hideMenu.value) {
          hideMenu.value = true;
          if (!isFirst) {
            menuDrawerVisible.value = true;
          }
        }
      } else {
        if (hideMenu.value) {
          hideMenu.value = false;
          menuDrawerVisible.value = false;
        }
      }
      isFirst = false;
    },
    {
      immediate: true,
    }
  );
  const info = authCache.getUserInfo();
  if (info) {
    userInfo.value = info;
  } else {
    doLogout();
  }
  // createConnection();
});
onBeforeUnmount(() => {
  resizer.remove(resizerId);
});

function onSubMenuOpenChange(keys) {
  subMenuSelKeys.value = keys;
}
const menuDrawerVisible = ref(false);
function pushRoute(route?: string) {
  // if (!userStore.getPermissionByAction(route as string)) {
  //   router.push("/" + curAppUrl + "/401");
  //   return;
  // }
  console.log(route);
  homeStore.togglePageLoading({ loading: true });
  router.push(route || "404").catch((e) => {
    const curAppUrl = homeStore.applicationData[0].url;
    router.push(curAppUrl + "/404");
  });
}
function doLogout() {
  pushRoute("/login");
}
</script>
<style lang="less">
.sider-trigger {
  position: absolute;
  bottom: 8px;
  right: 8px;
}
.ant-layout-sider-collapsed {
  .sider-trigger {
    left: 0;
    right: 0;
    text-align: center;
  }
}
.ant-scrolling-effect {
  > .ant-layout-content {
    overflow: hidden;
  }
}
</style>
